package com.gui.chat01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Server {
    private Map<String,MyThread> clients = null;

    public static void main(String[] args) {
        new Server().startup();
    }

    public void startup(){
        ServerSocket ss = null;

        //实例化服务器端socket，需要制定服务器的端口号
        //注意端口号一般自己定义，最大可以取到65535，并且不能小于1024
        try {
            ss = new ServerSocket(8888);
            clients = new HashMap<String,MyThread>();
            System.out.println("---服务器端启动---");
            //服务器应该一直等着客户端来连接,所以应该是一个死循环
            while(true){
                Socket s = ss.accept();
                //启动一个线程，在线程内部直接操作
                MyThread mt = new MyThread(s);
                new Thread(mt).start();
            }

        } catch (IOException e) {
            System.out.println("异常了");
            e.printStackTrace();
        } finally{
            try {
                if(ss != null){
                    ss.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    private class MyThread implements Runnable{
        private Socket s;
        private BufferedReader br;
        private PrintWriter out;
        private String socketName = null;
        private boolean flag = true;
        private String userName = null;
        public MyThread(Socket s) throws IOException{
            this.s = s;
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new PrintWriter(s.getOutputStream(),true);
            userName = br.readLine();
            socketName = userName + "---" + s.getInetAddress().getHostAddress() + ":" + s.getPort();
            clients.put(socketName,this);
            System.out.println("[" +socketName + "]" + "----连接了!");
            //通知所有人XXX上线了
            send("[" +socketName + "]" + "----上线了!");
            sendUser();
        }

        public void sendUser(){
            String us = "users:";
            Set<String> keys = clients.keySet();
            for(String k : keys){
                us += k + ",";
            }
            send(us);
        }

        public void stop(){
            flag = false;
            clients.remove(socketName);
            sendUser();
        }

        public void send(String msg){
            Set<String> keys = clients.keySet();
            for(String k : keys){
                clients.get(k).out.println(msg);
            }
        }

        //截取所有用户
        public String getUsersByMsg(String msg){
            String str = msg.substring("to:".length(),msg.indexOf(":end"));
            return str;
        }

        //截取信息
        public String formartMsg(String msg){
            String str = msg.substring(msg.indexOf(":end") + ":end".length());
            return str;
        }

        //发送给特定用户
        public void sendUsers(String us,String msg){
            String [] users = us.split(",");
            for(String u : users){
                clients.get(u).out.println("[" + socketName + "]" + ":" + msg + "[私]");
            }
        }

        @Override
        public void run() {
            try {
                while(true){
                    if(!flag) break;

                    String str = br.readLine();

                    if(str.equalsIgnoreCase("quit")){
                        stop();
                        out.println("disconnect");
                        break;
                    }
                    System.out.println(socketName + "说:"+ str);

                    String us = getUsersByMsg(str);
                    String msg = formartMsg(str);
                    if(us.equals("all")){
                        send("[" + socketName + "]" + ":" + msg + "[群]");
                    }else{
                        sendUsers(us,msg);
                    }
                }
            }catch(SocketException e){
                stop();
                System.out.println("客户端非正常退出!");
            }catch (IOException e) {
                stop();
                System.out.println("客户端非正常退出!");
                //e.printStackTrace();
            } finally{
                try {
                    if(this.s!=null){
                        this.s.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }

    }




}
